package net.homelinux.chaoswg.io.renga.core.gui.operations.reader;

import java.awt.Point;

import net.homelinux.chaoswg.io.higherorderfunctions.AbstractBinaryFunction;
import net.homelinux.chaoswg.io.higherorderfunctions.BinaryFunction;
import net.homelinux.chaoswg.io.renga.core.gui.operations.Operation;
import net.homelinux.chaoswg.io.renga.core.registries.ConnectionRegistry;
import net.homelinux.chaoswg.io.renga.core.registries.OperationLoadRegistry;

import org.jdom.Element;

public class CommonOperationReader extends AbstractBinaryFunction<Operation, Operation, Element> implements BinaryFunction<Operation, Operation, Element>{

    public Operation apply(final Operation arg0, final Element arg1) throws IllegalArgumentException {
        arg0.setId(Integer.parseInt(arg1.getAttributeValue("id")));
        
        arg0.initConnections(Integer.parseInt(arg1.getChild("connections").getAttributeValue("total")));
        
        final Element ve = arg1.getChild("visualisation");
        final int x = Integer.parseInt(ve.getChildText("x"));
        final int y = Integer.parseInt(ve.getChildText("y"));
        
        arg0.moveTo(new Point (x,y));
        
        final ConnectionRegistry cr = ConnectionRegistry.getConnectoRegistry();
        cr.setElement(arg0, arg1);

        final OperationLoadRegistry olr = OperationLoadRegistry.getOperationRegistry();
        olr.setOperationReader(arg0.getId(), arg0);
        
        return arg0;
    }
}
